package com.ashley.phonemsn

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import com.ashley.phonemsn.ContactManager.Contact
import com.ashley.phonemsn.ui.theme.PhoneMSNTheme
import java.util.Locale

@OptIn(ExperimentalMaterial3Api::class)
class ContactActivity : ComponentActivity() {
    private val TAG = "ContactActivity"
    private lateinit var contactManager: ContactManager
    private var contacts = mutableStateListOf<Contact>()
    private var searchQuery by mutableStateOf("")
    private var showAddContactDialog by mutableStateOf(false)
    private var selectedContact by mutableStateOf<Contact?>(null)
    private var showEditContactDialog by mutableStateOf(false)
    
    // 权限请求
    private val requestContactsPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val readGranted = permissions[Manifest.permission.READ_CONTACTS] ?: false
        val writeGranted = permissions[Manifest.permission.WRITE_CONTACTS] ?: false
        
        if (readGranted) {
            loadContacts()
        }
    }
    
    companion object {
        const val EXTRA_PHONE_NUMBER = "com.ashley.phonemsn.EXTRA_PHONE_NUMBER"
        const val EXTRA_CONTACT_NAME = "com.ashley.phonemsn.EXTRA_CONTACT_NAME"
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        contactManager = ContactManager(this)
        checkPermissions()
        
        setContent {
            PhoneMSNTheme {
                ContactScreen()
            }
        }
    }
    
    private fun checkPermissions() {
        val readContactsPermission = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.READ_CONTACTS
        )
        
        val writeContactsPermission = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.WRITE_CONTACTS
        )
        
        if (readContactsPermission != PackageManager.PERMISSION_GRANTED ||
            writeContactsPermission != PackageManager.PERMISSION_GRANTED) {
            requestContactsPermissionLauncher.launch(
                arrayOf(
                    Manifest.permission.READ_CONTACTS,
                    Manifest.permission.WRITE_CONTACTS
                )
            )
        } else {
            loadContacts()
        }
    }
    
    private fun loadContacts() {
        val allContacts = contactManager.getAllContacts()
        contacts.clear()
        contacts.addAll(allContacts)
    }
    
    private fun onContactSelected(contact: Contact) {
        // 通过Intent返回选择的电话号码和联系人名称
        val resultIntent = Intent()
        resultIntent.putExtra(EXTRA_PHONE_NUMBER, contact.phoneNumber)
        resultIntent.putExtra(EXTRA_CONTACT_NAME, contact.name)
        setResult(RESULT_OK, resultIntent)
        finish()
    }
    
    @Composable
    fun ContactScreen() {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("通讯录") },
                    actions = {
                        IconButton(onClick = { showAddContactDialog = true }) {
                            Icon(Icons.Default.PersonAdd, contentDescription = "添加联系人")
                        }
                    }
                )
            }
        ) { padding ->
            Column(modifier = Modifier
                .padding(padding)
                .fillMaxSize()
            ) {
                // 搜索栏
                SearchBar()
                
                // 联系人列表
                ContactList()
            }
        }
        
        // 添加联系人对话框
        if (showAddContactDialog) {
            AddEditContactDialog(
                isEdit = false,
                contact = null,
                onSave = { name, number ->
                    if (contactManager.addContact(name, number)) {
                        loadContacts()
                        showAddContactDialog = false
                    }
                },
                onDismiss = { showAddContactDialog = false }
            )
        }
        
        // 编辑联系人对话框
        if (showEditContactDialog && selectedContact != null) {
            AddEditContactDialog(
                isEdit = true,
                contact = selectedContact,
                onSave = { name, number ->
                    if (contactManager.updateContact(selectedContact!!.id, name, number)) {
                        loadContacts()
                        showEditContactDialog = false
                        selectedContact = null
                    }
                },
                onDismiss = {
                    showEditContactDialog = false
                    selectedContact = null
                }
            )
        }
    }
    
    @Composable
    fun SearchBar() {
        TextField(
            value = searchQuery,
            onValueChange = { searchQuery = it },
            leadingIcon = { Icon(Icons.Default.Search, contentDescription = "搜索") },
            trailingIcon = {
                if (searchQuery.isNotEmpty()) {
                    IconButton(onClick = { searchQuery = "" }) {
                        Icon(Icons.Default.Close, contentDescription = "清除")
                    }
                }
            },
            placeholder = { Text("搜索联系人") },
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp),
            colors = TextFieldDefaults.colors(
                focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant,
                unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent
            ),
            shape = MaterialTheme.shapes.medium
        )
    }
    
    @Composable
    fun ContactList() {
        val filteredContacts = if (searchQuery.isEmpty()) {
            contacts
        } else {
            contactManager.searchContacts(searchQuery)
        }
        
        if (filteredContacts.isEmpty()) {
            Column(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Icon(
                    Icons.Default.PersonOff,
                    contentDescription = "无联系人",
                    modifier = Modifier.size(64.dp),
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = if (searchQuery.isEmpty()) "暂无联系人" else "未找到匹配的联系人",
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 16.dp)
                )
            }
        } else {
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(filteredContacts) { contact ->
                    ContactItem(contact)
                }
            }
        }
    }
    
    @Composable
    fun ContactItem(contact: Contact) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp, vertical = 4.dp)
                .clickable {
                    onContactSelected(contact)
                }
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 头像
                Box(
                    modifier = Modifier
                        .size(48.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = contact.name.take(1).uppercase(Locale.getDefault()),
                        color = Color.White,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
                
                Spacer(modifier = Modifier.width(16.dp))
                
                // 联系人信息
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = contact.name,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium
                    )
                    Text(
                        text = contact.phoneNumber,
                        fontSize = 14.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                // 编辑按钮
                IconButton(onClick = {
                    selectedContact = contact
                    showEditContactDialog = true
                }) {
                    Icon(Icons.Default.Edit, contentDescription = "编辑")
                }
                
                // 删除按钮
                IconButton(onClick = {
                    contactManager.deleteContact(contact.id)
                    loadContacts()
                }) {
                    Icon(Icons.Default.Delete, contentDescription = "删除")
                }
            }
        }
    }
    
    @Composable
    fun AddEditContactDialog(
        isEdit: Boolean,
        contact: Contact?,
        onSave: (String, String) -> Unit,
        onDismiss: () -> Unit
    ) {
        var name by remember { mutableStateOf(contact?.name ?: "") }
        var phoneNumber by remember { mutableStateOf(contact?.phoneNumber ?: "") }
        var errorMessage by remember { mutableStateOf("") }
        
        AlertDialog(
            onDismissRequest = onDismiss,
            title = { Text(text = if (isEdit) "编辑联系人" else "添加联系人") },
            text = {
                Column(modifier = Modifier.fillMaxWidth()) {
                    OutlinedTextField(
                        value = name,
                        onValueChange = { name = it },
                        label = { Text("联系人姓名") },
                        modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)
                    )
                    OutlinedTextField(
                        value = phoneNumber,
                        onValueChange = { 
                            // 只允许输入数字和+号
                            if (it.all { char -> char.isDigit() || char == '+' } || it.isEmpty()) {
                                phoneNumber = it
                            }
                        },
                        label = { Text("电话号码") },
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.Phone,
                            imeAction = ImeAction.Done
                        ),
                        modifier = Modifier.fillMaxWidth()
                    )
                    if (errorMessage.isNotEmpty()) {
                        Text(
                            text = errorMessage,
                            color = MaterialTheme.colorScheme.error,
                            fontSize = 12.sp,
                            modifier = Modifier.padding(top = 4.dp)
                        )
                    }
                }
            },
            confirmButton = {
                Button(onClick = {
                    errorMessage = ""
                    if (name.isBlank()) {
                        errorMessage = "请输入联系人姓名"
                    } else if (phoneNumber.isBlank()) {
                        errorMessage = "请输入电话号码"
                    } else if (phoneNumber.length < 5) {
                        errorMessage = "电话号码太短"
                    } else {
                        onSave(name, phoneNumber)
                    }
                }) {
                    Text(if (isEdit) "保存" else "添加")
                }
            },
            dismissButton = {
                TextButton(onClick = onDismiss) {
                    Text("取消")
                }
            }
        )
    }
}